$(document).ready(function () {
    var $toggleButton = $("#toggleButton");
    var $selectDropdown = $("#selectDropdown");
    var $selectBox = $("#selectBox");
    var $selectedContainer = $selectBox.find(".selected-container");
    var $selectOptions = $selectDropdown.find(".option");
    var $errorMessage = $("#error-message");
    var selectedValues = new Set();
    var maxSelections = 5; // Set the limit to 5 selected items
    var minSelections = 1; // Minimum selection is 1 item

    $selectBox.css("height", "45px");

    $toggleButton.on("click", function () {
        if ($selectDropdown.hasClass("show")) {
            $selectDropdown.removeClass("show");
            $toggleButton.text("选择元素");
        } else {
            $selectDropdown.addClass("show");
            $toggleButton.text("收起");
        }
    });

    $selectOptions.on("click", function () {
        var selectedValue = $(this).attr("value");
        if (!selectedValues.has(selectedValue)) {
            if (selectedValues.size < maxSelections) {
                addSelectedItem(selectedValue);
                $(this).addClass("disabled");
                $errorMessage.hide(); // Hide error message when a valid selection is made
            } else {
                showErrorMessage("最多只能选择 " + maxSelections + " 个元素");
            }
        }
    });

    function addSelectedItem(value) {
        selectedValues.add(value);
        var $selectedItem = $("<div>").addClass("selected-item").text(value).attr("data-value", value);
        var $removeIcon = $("<span>").addClass("remove-icon").text("X").on("click", function (event) {
            event.stopPropagation();
            if (selectedValues.size > minSelections) {
                removeSelectedItem(value);
            } else {
                showErrorMessage("至少需要选择一个元素");
            }
        });

        $selectedItem.append($removeIcon);
        $selectedContainer.append($selectedItem);

        adjustHeight();
    }

    function removeSelectedItem(value) {
        selectedValues.delete(value);
        var $selectedItem = $selectedContainer.find(`.selected-item[data-value="${value}"]`);
        $selectedItem.remove();

        $selectOptions.each(function () {
            if ($(this).attr("value") === value) {
                $(this).removeClass("disabled");
            }
        });

        adjustHeight();
        $errorMessage.hide(); // Hide error message when item is successfully removed
    }

    function adjustHeight() {
        var rows = Math.ceil($selectedContainer.outerHeight() / 45);
        $selectBox.css("height", Math.max(rows * 45, 45) + "px");
    }

    function showErrorMessage(message) {
        $errorMessage.text(message).show();
    }
});